/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.matrimonyapp;

import com.matrimonybeans.ChangeAvatarLocal;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author ChauAnh
 */
public class ChangeAvatar extends HttpServlet {

    @EJB
    private ChangeAvatarLocal changeAvatar;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileRoot = item.getName();
                        //Lấy phan mở rong cua file
                        int i = fileRoot.lastIndexOf('.');
                        String ext = null;
                        if (i > 0 && i < fileRoot.length() - 1) {
                            ext = fileRoot.substring(i + 1).toLowerCase();
                        }
                        //Lay ngay thang hien tai
                        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        Date dateObj = new Date();
                        String date = dateFormat.format(dateObj);
                        String fileName = request.getSession().getAttribute("login") + date + "." + ext;
                        String fileNameDelete = request.getSession().getAttribute("avatar").toString();
                        //Lấy duong dan
                        String root = getServletContext().getRealPath("/");
                        //Lấy đường dẫn của thư mục avatar chua bulding
                        char pathArr[] = root.toCharArray();
                        int lengPath = root.length() - 43;
                        String pathRoot = "";
                        for (int j = 0; j < lengPath; j++) {
                            pathRoot = pathRoot + pathArr[j];
                        }

                        if (fileProcess(fileName, fileNameDelete, root, item)) {
                                if (changeAvatar.updateAvatar(request.getSession().getAttribute("login").toString(), fileName)) {
                                    HttpSession ss = request.getSession(true);
                                    ss.removeAttribute("avatar");
                                    ss.setAttribute("avatar", fileName);
                                    out.println("<script type='text/javascript'>alert('Avatar changed success!');window.location.href = 'index.jsp';</script>");
                                } else {
                                    out.println("<script type='text/javascript'>alert('Avatar changed unsuccess!');history.go(-1);</script>");
                                }
                            } else {
                                out.println("<script type='text/javascript'>alert('Avatar changed unsuccess!');history.go(-1);</script>");
                            }
//                        if (fileProcess(fileName, fileNameDelete, pathRoot + File.separator + "Matrimony-war" + File.separator + "web", item)) {
//                            
//                        } else {
//                            out.println("<script type='text/javascript'>alert('Avatar changed unsuccess!');history.go(-1);</script>");
//                        }

                    }
                }
            } catch (Exception ex) {
                out.println(ex);
            }
        }
        out.close();
    }

    public static boolean fileProcess(String fileName, String fileNameDelete, String pathRoot, FileItem item) {
        try {
            String pathFolder = pathRoot + "/avatar";
            File pathFile = new File(pathFolder + "/" + fileName);
            File pathDelete = new File(pathFolder + "/" + fileNameDelete);
            //Kiem tra ton tai cua file anh
            if (pathDelete.exists()) {
                //Xoa file anh
                //System.out.println("Kiem tra file delete da ton tai!"+ pathRoot);
                if (pathDelete.delete()) {
                    //System.out.println(" file delete da thanh cong!");
                    //Kiem tra ton tai cau duong dan
                    File pathAdd = new File(pathFolder);
                    if (pathAdd.exists()) {
                        item.write(pathFile);
                        pathFile.createNewFile();
                        return true;
                    }
                }
            } else {
                //Kiem tra ton tai cau duong dan
                File pathAdd = new File(pathFolder);
                if (pathAdd.exists()) {
                    item.write(pathFile);
                    pathFile.createNewFile();
                    return true;
                }
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
